<template>
  <div class="activity-edit-container">
    <el-card class="form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">编辑活动</span>
          <el-button @click="$router.back()">
            <IconifyIconOffline icon="ep:back" class="mr-1" />
            返回
          </el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="activity-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="活动名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入活动名称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="活动类型" prop="type">
                <el-select
                  v-model="form.type"
                  placeholder="请选择活动类型"
                  style="width: 100%"
                >
                  <el-option label="篮球" value="basketball" />
                  <el-option label="羽毛球" value="badminton" />
                  <el-option label="足球" value="football" />
                  <el-option label="网球" value="tennis" />
                  <el-option label="乒乓球" value="pingpong" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="活动状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio value="draft">草稿</el-radio>
              <el-radio value="published">已发布</el-radio>
              <el-radio value="ongoing">进行中</el-radio>
              <el-radio value="completed">已结束</el-radio>
              <el-radio value="cancelled">已取消</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="活动描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="请输入活动描述"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="活动封面" prop="cover">
            <el-upload
              class="cover-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeCoverUpload"
              :http-request="handleCoverUpload"
            >
              <img v-if="form.cover" :src="form.cover" class="cover-image" />
              <div v-else class="cover-placeholder">
                <IconifyIconOffline icon="ep:plus" class="upload-icon" />
                <div class="upload-text">点击上传封面</div>
                <div class="upload-tip">支持 JPG、PNG 格式，建议尺寸 16:9</div>
              </div>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 时间和地点 -->
        <div class="form-section">
          <div class="section-title">时间和地点</div>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="form.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="form.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="省份" prop="province">
                <el-select
                  v-model="form.province"
                  placeholder="请选择省份"
                  style="width: 100%"
                >
                  <el-option label="北京市" value="北京市" />
                  <el-option label="上海市" value="上海市" />
                  <el-option label="广东省" value="广东省" />
                  <el-option label="浙江省" value="浙江省" />
                  <el-option label="江苏省" value="江苏省" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="城市" prop="city">
                <el-select
                  v-model="form.city"
                  placeholder="请选择城市"
                  style="width: 100%"
                >
                  <el-option label="北京市" value="北京市" />
                  <el-option label="上海市" value="上海市" />
                  <el-option label="广州市" value="广州市" />
                  <el-option label="深圳市" value="深圳市" />
                  <el-option label="杭州市" value="杭州市" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="区县" prop="district">
                <el-input v-model="form.district" placeholder="请输入区县" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入详细地址" />
          </el-form-item>

          <el-form-item label="场地名称" prop="venue">
            <el-input v-model="form.venue" placeholder="请输入场地名称" />
          </el-form-item>
        </div>

        <!-- 报名设置 -->
        <div class="form-section">
          <div class="section-title">报名设置</div>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报名人数" prop="maxParticipants">
                <el-input-number
                  v-model="form.maxParticipants"
                  :min="1"
                  :max="10000"
                  placeholder="请输入最大报名人数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="费用类型" prop="feeType">
                <el-radio-group v-model="form.feeType">
                  <el-radio value="free">免费</el-radio>
                  <el-radio value="paid">收费</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="form.feeType === 'paid'" :gutter="20">
            <el-col :span="12">
              <el-form-item label="活动费用" prop="fee">
                <el-input-number
                  v-model="form.fee"
                  :min="0"
                  :precision="2"
                  placeholder="请输入活动费用"
                  style="width: 100%"
                >
                  <template #prepend>¥</template>
                </el-input-number>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="收费方式" prop="paymentMethod">
                <el-select
                  v-model="form.paymentMethod"
                  placeholder="请选择收费方式"
                  style="width: 100%"
                >
                  <el-option label="线上支付" value="online" />
                  <el-option label="线下支付" value="offline" />
                  <el-option label="预付款" value="prepaid" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报名权限" prop="signUpType">
                <el-select
                  v-model="form.signUpType"
                  placeholder="请选择报名权限"
                  style="width: 100%"
                >
                  <el-option label="所有人" value="public" />
                  <el-option label="俱乐部成员" value="club" />
                  <el-option label="邀请码" value="invite" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col v-if="form.signUpType === 'invite'" :span="12">
              <el-form-item label="邀请码" prop="inviteCode">
                <el-input
                  v-model="form.inviteCode"
                  placeholder="请输入邀请码"
                  maxlength="6"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="其他设置">
                <el-checkbox v-model="form.allowWaitlist">允许候补</el-checkbox>
                <el-checkbox v-model="form.allowTransfer">允许转让</el-checkbox>
                <el-checkbox v-model="form.allowBringGuest"
                  >允许带人</el-checkbox
                >
                <el-checkbox v-model="form.isPublic">公开活动</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 联系信息 -->
        <div class="form-section">
          <div class="section-title">联系信息</div>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactName">
                <el-input
                  v-model="form.contactName"
                  placeholder="请输入联系人姓名"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input
                  v-model="form.contactPhone"
                  placeholder="请输入联系电话"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="微信号" prop="wechat">
            <el-input
              v-model="form.wechat"
              placeholder="请输入微信号"
              style="width: 300px"
            />
          </el-form-item>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button size="large" @click="$router.back()">取消</el-button>
          <el-button size="large" @click="handleSaveDraft">保存草稿</el-button>
          <el-button
            type="primary"
            size="large"
            :loading="submitting"
            @click="handleSubmit"
          >
            保存修改
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, type FormInstance, type UploadProps } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";

const route = useRoute();
const router = useRouter();
const formRef = ref<FormInstance>();
const submitting = ref(false);

// 表单数据
const form = reactive({
  id: 0,
  name: "",
  type: "",
  status: "draft",
  description: "",
  cover: "",
  startTime: "",
  endTime: "",
  province: "",
  city: "",
  district: "",
  address: "",
  venue: "",
  maxParticipants: 50,
  feeType: "free",
  fee: 0,
  paymentMethod: "",
  signUpType: "public",
  inviteCode: "",
  allowWaitlist: false,
  allowTransfer: false,
  allowBringGuest: false,
  isPublic: true,
  contactName: "",
  contactPhone: "",
  wechat: ""
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入活动名称", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "活动名称长度在 2 到 50 个字符",
      trigger: "blur"
    }
  ],
  type: [{ required: true, message: "请选择活动类型", trigger: "change" }],
  description: [
    { required: true, message: "请输入活动描述", trigger: "blur" },
    {
      min: 10,
      max: 500,
      message: "活动描述长度在 10 到 500 个字符",
      trigger: "blur"
    }
  ],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }],
  province: [{ required: true, message: "请选择省份", trigger: "change" }],
  city: [{ required: true, message: "请选择城市", trigger: "change" }],
  address: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  venue: [{ required: true, message: "请输入场地名称", trigger: "blur" }],
  maxParticipants: [
    { required: true, message: "请输入报名人数", trigger: "blur" }
  ],
  fee: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (form.feeType === "paid" && (!value || value <= 0)) {
          callback(new Error("收费活动请输入大于0的费用"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  paymentMethod: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (form.feeType === "paid" && !value) {
          callback(new Error("请选择收费方式"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  inviteCode: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (form.signUpType === "invite" && !value) {
          callback(new Error("请输入邀请码"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  contactName: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" }
  ],
  contactPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ]
};

// 封面上传前检查
const beforeCoverUpload: UploadProps["beforeUpload"] = rawFile => {
  const isJPGOrPNG =
    rawFile.type === "image/jpeg" || rawFile.type === "image/png";
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isJPGOrPNG) {
    ElMessage.error("封面图片只能是 JPG/PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("封面图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 处理封面上传
const handleCoverUpload = (options: any) => {
  // 这里应该上传到服务器，现在模拟一个URL
  const reader = new FileReader();
  reader.onload = e => {
    form.cover = e.target?.result as string;
  };
  reader.readAsDataURL(options.file);
};

// 保存草稿
const handleSaveDraft = async () => {
  form.status = "draft";
  await handleSubmit(false);
};

// 提交表单
const handleSubmit = async (validate = true) => {
  if (validate && !formRef.value) return;

  try {
    if (validate) {
      await formRef.value!.validate();

      // 验证时间
      if (new Date(form.startTime) >= new Date(form.endTime)) {
        ElMessage.error("结束时间必须大于开始时间");
        return;
      }
    }

    submitting.value = true;

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 这里应该调用更新活动的API
    console.log("更新活动数据:", form);

    ElMessage.success(
      form.status === "draft" ? "草稿保存成功" : "活动更新成功"
    );
    router.push("/activity/list");
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitting.value = false;
  }
};

// 加载活动详情
const loadActivityDetail = async () => {
  const activityId = route.params.id;

  // 模拟从API获取活动详情
  const mockData = {
    id: Number(activityId),
    name: "周末羽毛球友谊赛",
    type: "badminton",
    status: "ongoing",
    description:
      "欢迎所有羽毛球爱好者参加我们的周末友谊赛！无论你是初学者还是高手，都能在这里找到合适的对手。",
    cover:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=badminton%20court%20with%20players%20in%20action%2C%20modern%20sports%20facility%2C%20bright%20lighting&image_size=landscape_16_9",
    startTime: "2024-01-20 14:00:00",
    endTime: "2024-01-20 18:00:00",
    province: "广东省",
    city: "深圳市",
    district: "南山区",
    address: "科技园南区深南大道9988号",
    venue: "深圳湾体育中心羽毛球馆",
    maxParticipants: 20,
    feeType: "paid",
    fee: 50,
    paymentMethod: "online",
    signUpType: "public",
    inviteCode: "",
    allowWaitlist: true,
    allowTransfer: true,
    allowBringGuest: false,
    isPublic: true,
    contactName: "张教练",
    contactPhone: "13800138000",
    wechat: "coach_zhang"
  };

  // 填充表单数据
  Object.assign(form, mockData);
};

onMounted(() => {
  loadActivityDetail();
});
</script>

<style scoped lang="scss">
.activity-edit-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.form-card {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
}

.activity-form {
  padding: 20px 0;
}

.form-section {
  margin-bottom: 40px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
  position: relative;

  &::after {
    content: "";
    position: absolute;
    left: 0;
    bottom: -2px;
    width: 30px;
    height: 2px;
    background-color: #409eff;
  }
}

.cover-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }
  }
}

.cover-image {
  width: 300px;
  height: 169px;
  object-fit: cover;
  display: block;
}

.cover-placeholder {
  width: 300px;
  height: 169px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;

  .upload-icon {
    font-size: 28px;
    color: #8c939d;
    margin-bottom: 8px;
  }

  .upload-text {
    color: #606266;
    font-size: 14px;
    margin-bottom: 4px;
  }

  .upload-tip {
    color: #909399;
    font-size: 12px;
  }
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .activity-edit-container {
    padding: 10px;
  }

  .form-card {
    margin: 0;
  }

  .cover-image,
  .cover-placeholder {
    width: 100%;
    max-width: 300px;
  }
}
</style>
